package controller

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"house-property/common"
	"house-property/model"
	"net/http"
	"strconv"
)

func Redistributehou(ctx *gin.Context){
	DB := common.InitDB()
	b, _ := ctx.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	unum := m["num"]
	udepartment := m["department"]
	uprofessional :=m["professional"]
	upopulation :=m["population"]
	uarea :=m["area"]
	uonum :=m["onum"]
	urarea :=m["rarea"]
	u,_:=strconv.Atoi(upopulation)
	if !isTelephoneExist(DB,unum){
		ctx.JSON(http.StatusOK,gin.H{
			"code":1000,
			"msg":"手机号码输入错误，请重新输入",
		})
		return
	}
	if len(udepartment) == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 1001,
			"msg":  "部门不能为空",
		})
		return
	}
	if u == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 1002,
			"msg":  "家庭人口数不能为空",
		})
		return
	}
	if len(udepartment) == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 1003,
			"msg":  "部门不能为空",
		})
		return
	}
	if len(uarea) == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 1004,
			"msg":  "原住房面积不能为空",
		})
		return
	}
	if len(uonum ) == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 1005,
			"msg":  "原房号不能为空",
		})
		return
	}
	if len(urarea) == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 1006,
			"msg":  "要求住房面积不能为空",
		})
		return
	}
	var hou model.House
	DB.Where("Unum = ?", unum).Delete(&hou)
	var d model.Hou_property
	DB.Model(&d).Where("Hnum = ?",uonum  ).Update("hallocation", "否")//修改符号为是
	housing_sco:=calculcation(DB,uprofessional,u,udepartment )

	newUser := model.Separate_ro{
		Unum: unum,
		Udepartment: udepartment,
		Upopulation: u,
		Uprofessional: uprofessional,
		Housing_sco: housing_sco,
		Urequire_hs_ar:urarea ,
	}
	//log.Println(newUser.Housing_sco)
	DB.Create(&newUser)
	ctx.JSON(200, gin.H{
		"code":200,
		"msg": "您已成功提交调房申请",
	})

}
